<template>
	<Modal
		ref 		= 'modalRef' 
		:title 		= 'modalConfig?.title || title' 
		@ok 		= 'onOk' 
		@close 		= 'onClose' 
		:width 		= 'modalConfig.width'
		:height 	= 'modalConfig.height'
		:loading 	= 'ajax.loading'
		:controls 	= 'modalConfig?.controls'
		:scroll 	= 'false'
		:bodyStyle  = "searchConfig?.data ? {padding:'0 10px 0'} :{padding:'10px 10px 0'} "
		:destroy  	= "modalConfig.destroy === false ? false : true"
	>
		<SearchTable ref='modalTableRef' :search='searchConfig' :table='tableConfig' :page='false' @init='onInit'/>
	</Modal>
</template>

<script setup>
	import { watch } from 'vue'
	import Table from '@antd/table.vue'
	import SubmitUtils from '#cpt/utils/submit'
	/* --------------------------- Component --------------------------- */
	const Modal 		= $.lazy(()=>import('@antd/modal.vue'))
	const SearchTable 	= $.lazy(()=>import('#cpt/temp/SearchTable.vue'))
	/* --------------------------- props --------------------------- */
	const props = defineProps({
		data 	 	: { type:Array, default: [] },
		control   	: { type:Object, default: {} },
		config   	: { type:Object, default: {} },
		loading  	: Boolean,
		title 	 	: String
	})
	const { config, table, search }  = props
	/* --------------------------- 两种传值方式 --------------------------- */	/* --------------------------- ref --------------------------- */
	let modalRef 		= $ref()
	let modalTableRef 	= $ref()
	let ajax 			= $ref({})
	let tableModalConfig = $ref(config ?? {})
	let modalConfig 	= $ref(config?.modal ?? {})
	let searchConfig 	= $ref(config?.search ?? {})
	let tableConfig 	= $ref(config?.table ?? {})
	/* --------------------------- emit --------------------------- */
	const emit = defineEmits(['ok','submit', 'init'])
	const onOk = close => {
		const { row } = tableConfig
		const { keys } = row
		const { tableRef, keyStr='keys' } = tableModalConfig
		
		let param = { close, tableRef, modalTableRef }
		let submitParam = null
		
		if( row  ){
			const keys = row.keys
			const rows = row.rows
			param = { keys, rows, ...param }
			submitParam = ajax.ids ? {[keyStr]: keys} : keys
		}
		
		const { onOk, title } = modalConfig
		if(onOk){
			const bool = onOk(param)
			if( bool !== false){
				modalRef.close()
			}
		}else{
			SubmitUtils({ ajax, param:submitParam, submitConfig:tableModalConfig, title, modalRef, modalTableRef })
			return false
		}
	}
	const onClose = () => modalConfig?.onClose?.()
	
	const setBackInfo = async config => {
		let {
			tableRef,						/** @param {Object}				# 主表格 */
			// 添加与编辑
			label, 							/** @param {String}				# 按钮名称 */
			id, 							/** @param {Object}				# 表单配置 */
			bidStr=$config.pullIdName, 		/** @param {String}				# 回显 id */
			sidStr=$config.postIdName, 		/** @param {String}				# 提交 id 的参数名 */
			//
			keyStr, 						/** @param {String}				# 指定回显 keys 的字段 */
			// 回显
			infoApi, 						/** @param {String}				# 回显 api */
			onBackData,						/** @param {Function}			# 自定义回显 */
			backData, 						/** @param {Object, Function}	# 自定义回显 */
			// 流程函数
			onEnd,							/** @param {Object}				# 结束 */
			//
			param,							/** @param {Object}				# 提交参数 */
			backParam,						/** @param {Object}				# 回显参数 */
			abs, 							/** @param {Object}				# 回显参数是否是绝对参数 */
			// 
			start
		} = config
		
		if( !modalTableRef ) {
			return setTimeout(()=> setBackInfo( config ) ,100)
		}
		
		id = $fn.getResult(id)					// 必选参数 id
		param =  $fn.getResult(param)			// 提交参数
		backParam = $fn.getResult(backParam)	// 回显参数
		const backKeys = Boolean(config?.table?.row)
		const sendParam = { config, modalRef, tableRef, modalTableRef, start }
		ajax.ids = id ? { [sidStr]: id } : null
		// 接口回显
		if( infoApi ){
			if( !abs ){ backParam = { [bidStr]: id, ...backParam } }
			id = backParam ? null : id
			
			await $http.pull(ajax, infoApi, { id, param:backParam }).then(data=>{
				const p = {...sendParam, id, param, backParam, data }
				if( onBackData ){
					onBackData?.( p )
				}else{
					if(backData){
						backData = $fn.getResult(backData, p)
						if( backKeys ){
							modalTableRef.setKeys( backData )
						}
					}else{
						if( backKeys ){
							if($fn.hasArray(data)){
								modalTableRef.setKeys( data )
							}else if($fn.hasObject(data)){
								modalTableRef.setKeys( data?.[keyStr] ?? [] )
							}
						}
					}
				}
				onEnd?.(p)
			})
		}else{
			// 本地数据回显
			if(backData){
				backData = $fn.getResult(backData, sendParam)
				if( backKeys ){
					modalTableRef.setKeys( backData )
				}
			}else{
				onBackData?.(sendParam)
			}
			onEnd?.(sendParam)
		}
	}
	/* --------------------------- 初始化 --------------------------- */
	const onInit = value => {
		const p = { ...value, modalRef, modalTableRef }
		emit('init', p)
		modalConfig?.onInit?.( p )
	}
	/* --------------------------- 通信 --------------------------- */
	defineExpose({
		open: async value => {
			if( value ){ tableModalConfig = value }
			
			modalRef.open()
			
			if( $fn.hasObject(tableModalConfig) ){
				let {
					modal={}, 						/** @param {Object}				# 按钮模式 */
					table={},						/** @param {Object}				# 按钮模式 */
					search={},						/** @param {Object}				# 按钮模式 */
					// 流程函数
					onStart, 						/** @param {Object}				# 开始 */
				} = tableModalConfig
				
				modalConfig = modal
				tableConfig = table
				searchConfig = search
				tableModalConfig.onSubmit = modal?.onSubmit || tableModalConfig?.onSubmit
				modalConfig.title = modal.title ?? label
				const start = await onStart?.() 				// 在操作之前运行
				
				tableModalConfig.start = start
				
				setBackInfo(tableModalConfig)
			}
		},
		close: () => modalRef.close(),
		tableRef: () => modalTableRef,
		modalRef: () => modalRef,
	})
</script>